package org.opsli.core.filters.interceptor;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.opsli.plugins.security.exception.errorcode.AuthErrorCodeEnum;
import org.opsli.plugins.security.utils.WebUtils;
import org.opsli.plugins.security.vo.AuthResultWrapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 网关拦截器
 * 非白名单的请求只能来自Gateway网关
 */
@Component
@Slf4j
public class GatewayInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String Gateway = request.getHeader("Gateway");
        //验证请求是否来自网关
        log.info("请求是否来自网关:{}", Gateway);
        if (!"123".equals(Gateway)) {
            AuthResultWrapper<?> customResultWrapper =
                    AuthResultWrapper.getCustomResultWrapper(AuthErrorCodeEnum.AUTH_AUTH_gateway);
            WebUtils.renderString(request, response, JSONUtil.toJsonStr(customResultWrapper));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("进入拦截器=======执行中========");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("进入拦截器=======执行后========");
    }
}
